﻿using Microsoft.AspNetCore.Mvc;
using Quartz;
using Schedule.Method;
using Schedule.RequestModel;

namespace Schedule.Controllers
{
    [Route("[controller]/[action]")]
    [ApiController]
    public class JobController : ControllerBase
    {
        private readonly ISchedulerFactory schedulerFactory;
        private readonly ILogger<JobController> logger;

        public JobController(ISchedulerFactory schedulerFactory, ILogger<JobController> logger)
        {
            this.schedulerFactory = schedulerFactory;
            this.logger = logger;
        }
        /// <summary>
        /// 添加一个预约执行的接口执行任务
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> Record(RecordRequest request, CancellationToken cancellationToken = default)
        {
            logger.LogInformation($"收到请求{request}当前系统时间DateTime.Now:{DateTime.Now}");
            if (request.Time < DateTime.Now)
            {
                var message = $"参数异常:Time has passed";
                logger.LogWarning(message);
                return BadRequest(message);
            }
            var guid = Guid.NewGuid().ToString("N");
            var scheduler = await schedulerFactory.GetScheduler(cancellationToken);
            await scheduler.Start(cancellationToken);
            var myjob = JobBuilder.Create<MessageLoadJob>().WithIdentity(guid).Build();
            DateTimeOffset defaultdto = new DateTimeOffset(Convert.ToDateTime(request.Time)).AddMinutes(1);
            myjob.JobDataMap.Add("request", request);
            ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity(guid)
                .WithCronSchedule(TimeHelper.TimeToCronString(request!.Time))
                .EndAt(defaultdto)
                .Build();
            await scheduler.ScheduleJob(myjob, trigger, cancellationToken);
            var result = Ok(new { jobId = guid, original = request });
            logger.LogInformation($"请求:{request}执行成功,jobId:{guid}");
            return result;
        }
        /// <summary>
        /// 违约一个接口任务
        /// </summary>
        /// <param name="JobId">预约时返回的任务Id</param>
        /// <param name="Sign">自验证签名</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult> Breach(string JobId, string? Sign, CancellationToken cancellationToken = default)
        {
            logger.LogInformation($"收到违约请求JobId:{JobId},sign:{Sign}");
            string message = "违约失败或中断";
            if (!string.IsNullOrEmpty(JobId))
            {
                var scheduler = await schedulerFactory.GetScheduler(cancellationToken);
                //await scheduler.Start();
                logger.LogInformation($"执行违约JobId:{JobId},sign:{Sign}");
                var delResult = await scheduler.DeleteJob(new JobKey(JobId), cancellationToken);
                if (delResult)
                {
                    logger.LogInformation($"执行违约成功JobId:{JobId},sign:{Sign}");
                    message = "违约成功";
                    return Ok(message);
                }
                else
                {
                    logger.LogInformation($"{message}JobId:{JobId},sign:{Sign}");
                    return BadRequest(message);
                }

            }
            return Ok(message);
        }
    }
}
